<?php

/* 监控 */
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\facade\Db;

class MonitorController extends AdminBaseController
{
    var $type=array("1"=>"视频通话","2"=>"语音通话");
        
    public function index()
    {
        
        $data = $this->request->param();
        $map=[];
        $map[]=['status','=','1'];
		
		$type=isset($data['type']) ? $data['type']: '';
        if($type!=''){
            $map[]=['type','=',$type];
        }

        $start_time=isset($data['start_time']) ? $data['start_time']: '';
        $end_time=isset($data['end_time']) ? $data['end_time']: '';
        if($start_time!=""){
           $map[]=['addtime','>=',strtotime($start_time)];
        }
        if($end_time!=""){
           $map[]=['addtime','<=',strtotime($end_time) + 60*60*24];
        }
		
		$uid=isset($data['uid']) ? $data['uid']: '';
        if($uid!=''){
            $map[]=['uid|liveuid','=',$uid];
        }
        
        $list = Db::name('conversa_log')
            ->where($map)
            ->order("id desc")
            ->paginate(10);
        
        $list->each(function($v,$k){
           $v['userinfo']= getUserInfo($v['uid']);
           $v['liveinfo']= getUserInfo($v['liveuid']);
           $v['pull_user']=PrivateKey_tx('http',$v['uid'].'_'.$v['showid'],0);
           $v['pull_live']=PrivateKey_tx('http',$v['liveuid'].'_'.$v['showid'],0);
           
           $cha=time()-$v['starttime'];
           $v['length']=getLength($cha);
           
           return $v; 
        });
        
        $list->appends($data);
        
        $page = $list->render();
        $this->assign("page", $page);
            
        $this->assign('list', $list);
        $this->assign('type', $this->type);

        return $this->fetch();
    }
    
    function stopRoom(){
        
        $data = $this->request->param();
        
        $id=isset($data['id']) ? $data['id']: '';
        
        if($id<1){
            $this->error("信息错误");
        }

        $info=Db::name('conversa_log')
                ->where(" id={$id} ")
                ->find();

        if(!$info){
            $this->error("通话不存在");
        }
        
        if($info['status'] ==0){
            $this->error("通话未接通");
        }
        
        if($info['status'] ==2){
            $this->error("通话已结束");
        }
        
        $nowtime=time();

        $data=[
            'status'=>2,
            'endtime'=>$nowtime,
        ];
        $length=$nowtime - $info['starttime'];

        $sendtype='1'; //主播给用户发
        if($length < 10){
            $votes=$info['total'];
            reduceVotes($info['liveuid'],$votes,$votes);
            
            Db::name('user_coinrecord')
                ->where("action in (2,3) and touid = {$info['liveuid']} and showid={$info['showid']}")
                ->update(['isdeduct'=>1]);

            $data['total']='0';
        }
        
        Db::name('conversa_log')->where("id={$info['id']}")->update($data);
        

        Db::name('user')->where("id={$info['uid']}")->update( ['online'=>3] );
        Db::name('user')->where("id={$info['liveuid']}")->update( ['online'=>3] );

        
        
        
        $content='通话时长 '.getLength($length,2);
        /* IM */
        /* 用户给主播发 */
        $ext=[
            'method'=>'call',
            'action'=>'9',
            'type'=>$info['type'],
            'content'=>$content,
        ];
        
        #构造高级接口所需参数
        $msg_content = array();
        //创建array 所需元素
        $msg_content_elem = array(
            'MsgType' => 'TIMCustomElem',       //自定义类型
            'MsgContent' => array(
                'Data' => json_encode($ext),
                'Desc' => '',
            )
        );
        //将创建的元素$msg_content_elem, 加入array $msg_content
        array_push($msg_content, $msg_content_elem);
        
        $account_id=(string)$info['uid'];
        $receiver=(string)$info['liveuid'];
        $api=getTxRestApi();
        $type= $sendtype==0 ? 1 : 2;
        $ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
        
        /* 主播给用户发 */
        $ext=[
            'method'=>'call',
            'action'=>'8',
            'type'=>$info['type'],
            'content'=>$content,
        ];
        
        #构造高级接口所需参数
        $msg_content = array();
        //创建array 所需元素
        $msg_content_elem = array(
            'MsgType' => 'TIMCustomElem',       //自定义类型
            'MsgContent' => array(
                'Data' => json_encode($ext),
                'Desc' => '',
            )
        );
        //将创建的元素$msg_content_elem, 加入array $msg_content
        array_push($msg_content, $msg_content_elem);
        
        $account_id=(string)$info['liveuid'];
        $receiver=(string)$info['uid'];
        $api=getTxRestApi();
        $type= $sendtype==1 ? 1 : 2;
        $ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
        
        $this->success("关闭成功");
    }
	
	
	
	//直播相关---关播
	public function zindex(){

		$config=getConfigPri();
		$this->config=$config;
		$this->assign('config', $config);
        
        $lists = Db::name("live")
            ->where(['islive'=>1,'isvideo'=>0])
			->order("starttime desc")
			->paginate(6);
        
        $lists->each(function($v,$k){
			$v['userinfo']=getUserInfo($v['uid']);

            $auth_url=PrivateKeyA('http',$v['stream'],0);
        
            $v['url']=$auth_url;
            return $v; 
        });

        $page = $lists->render();

    	$this->assign('lists', $lists);
    	$this->assign("page", $page);
    	return $this->fetch();
    }
    
	public function zfull(){
        $uid = $this->request->param('uid', 0, 'intval');
        
        $where['islive']=1;
        $where['uid']=$uid;
        
		$live=Db::name("live")->where($where)->find();
		$config=getConfigPri();
        
		if($live['title']=="")
		{
			$live['title']="直播监控后台";
		}
        
        if($config['cdn_switch']==5){
            $pull=$live['pull'];
        }else{
            $pull=urldecode(PrivateKeyA('http',$live['stream'],0));
        }
		$live['pull']=$pull;
		$this->assign('config', $config);
		$this->assign('live', $live);
        
		return $this->fetch();
	}
	
	/**
     * @desc 关播
     * @return void
     */
	public function zstopRoom(){
        
		$uid = $this->request->param('uid', 0, 'intval');
        $this->closeLive($uid);

		$this->success("操作成功！");
	}
	
	private function closeLive($uid){
		$where['islive']=1;
        $where['uid']=$uid;
        
		$liveinfo=Db::name("live")
            ->field("uid,showid,starttime,title,province,city,stream,lng,lat,type,type_val,liveclassid")
            ->where($where)
            ->find();
        
		Db::name("live")->where(" uid='{$uid}'")->delete();
        
		if($liveinfo){
			$liveinfo['endtime']=time();
			$liveinfo['time']=date("Y-m-d",$liveinfo['showid']);
            
            $where2=[];
            $where2['touid']=$uid;
            $where2['showid']=$liveinfo['showid'];
            
			$votes=Db::name("user_coinrecord")
				->where($where2)
				->sum('totalcoin');
			$liveinfo['votes']=0;
			if($votes){
				$liveinfo['votes']=$votes;
			}
            
            $stream=$liveinfo['stream'];
			$nums=zSize('user_'.$stream);

			hDel("livelist",$uid);
			delcache($uid.'_zombie');
			delcache($uid.'_zombie_uid');
			delcache('attention_'.$uid);
			delcache('user_'.$stream);
			
			
			$liveinfo['nums']=$nums;
			
			Db::name("live_record")->insert($liveinfo);
            

		}
	}
	
	//封禁直播间
	public function zbanRoom(){
		$rs=array('code'=>'0','msg'=>'封禁成功','info'=>array());
		$uid = $this->request->param('roomid', 0, 'intval');
		$length = $this->request->param('length');

        $this->closeLive($uid);
        $now=time();
        $type='';

        switch ($length) {
        	case '30min':
        		$endtime=$now+30*60;
        		$type='30min';
        		break;

        	case '1day':
        		$endtime=strtotime("+1 day");
        		$type='1day';
        		break;

        	case '7day':
        		$endtime=strtotime("+7 day");
        		$type='7day';
        		break;

        	case '15day':
        		$endtime=strtotime("+15 day");
        		$type='15day';
        		break;

        	case '30day':
        		$endtime=strtotime("+30 day");
        		$type='30day';
        		break;

        	case '90day':
        		$endtime=strtotime("+90 day");
        		$type='90day';
        		break;

        	case '180day':
        		$endtime=strtotime("+180 day");
        		$type='180day';
        		break;

        	case 'all':
        		$endtime=0;
        		$type='all';
        		break;
        	
        	default:
        		$endtime=0;
        		break;
        }


        $ban_info=Db::name("live_ban")->where(['liveuid'=>$uid])->find();
        if($ban_info){
        	$res=Db::name("live_ban")
                ->where(['liveuid'=>$uid])
                ->update(
                    ['superid'=>1,'endtime'=>$endtime,'type'=>$type]
                );
        }else{
        	$res=Db::name("live_ban")->insert(
        		[
        			'liveuid'=>$uid,
        			'superid'=>1,
        			'addtime'=>$now,
        			'endtime'=>$endtime,
        			'type'=>$type
        		]
        	);
        }

        if(!$res){
        	$rs['code']=1001;
        	$rs['msg']='封禁失败';
        	echo json_encode($rs);
        	return;
        }
        echo json_encode($rs);
	}	

}